<template>
  <el-main>
    <el-tabs v-if="type != 1" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="功能权限" name="user"></el-tab-pane>
      <el-tab-pane label="部门管理" name="branch"></el-tab-pane>
      <el-tab-pane label="区域设置" name="street"></el-tab-pane>
      <el-tab-pane label="领域设置" name="region"></el-tab-pane>
      <el-tab-pane label="产业设置" name="industry"></el-tab-pane>
      <el-tab-pane label="需求解决设置" name="demandSolve"></el-tab-pane>
      <el-tab-pane label="问卷服务设置" name="questionService"></el-tab-pane>
    </el-tabs>

    <div v-show="activeName == 'user'">
      <div class="flex" style="margin-bottom: 20px">
        <el-button type="primary" @click="addUser">创建账号</el-button>

        <div>
          <el-input v-model="keywords" clearable style="width: 300px; margin-left: 15px" placeholder="搜索公司、联系人"
            class="input-with-select" @change="getuserList">
            <el-button slot="append" style="background-color: #45a321; color: #fff; border-radius: 0"
              @click="getuserList">
              搜索
            </el-button>
            <i slot="prefix-icon" class="el-icon-search" />
          </el-input>
        </div>
      </div>

      <div>
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column prop="id" align="center" label="ID">
            <template slot-scope="scope">
              <div :style="{ color: scope.row.is_admin == 1 ? 'red' : '' }">
                {{ scope.row.id }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="region_name" align="center" label="账号名称">
            <template slot-scope="scope">
              <div :style="{ color: scope.row.is_admin == 1 ? 'red' : '#409eff' }" @click="setToken(scope.row)">
                {{ scope.row.region_name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="登录账号">
            <template slot-scope="scope">
              <div :style="{ color: scope.row.is_admin == 1 ? 'red' : '' }">
                {{ scope.row.login }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="username" align="center" label="联系人">
            <template slot-scope="scope">
              <div :style="{ color: scope.row.is_admin == 1 ? 'red' : '' }">
                {{ scope.row.username }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="mobile" align="center" label="联系方式">
            <template slot-scope="scope">
              <div :style="{ color: scope.row.is_admin == 1 ? 'red' : '' }">
                {{ scope.row.mobile }}
              </div>
            </template> </el-table-column>、

          <el-table-column prop="login" align="center" :label="type == 1 ? '监控区域' : '所在部门'">
            <template slot-scope="scope">
              <div :style="{ color: scope.row.is_admin == 1 ? 'red' : '' }">
                {{ type == 1 ? scope.row.back_name : scope.row.department_name }}
              </div>
            </template>
          </el-table-column>

          <el-table-column align="center" label="全局权限">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.is_queue" @change="updataQueue(scope.row.id)" active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column align="center" label="是否启用">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.switch" @change="updataState(scope.row.id)" active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </template>
          </el-table-column>

          <el-table-column prop="login" align="center" label="有效期" v-if="type == 1">
            <template slot-scope="scope">
              <div :style="{ color: scope.row.is_admin == 1 ? 'red' : '' }">
                {{ scope.row.over_on }}
              </div>
              <span class="over_on" v-if="isDateExpired(scope.row.over_on)">
                已过期
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="login" align="center" label="监控企业" v-if="type == 1">
            <template slot-scope="scope">
              <div class="company_count" v-if="scope.row.is_admin != 1" @click="ImportCompany(scope.row.region_id)"
                :style="{ color: scope.row.is_admin == 1 ? 'red' : '' }">
                {{ scope.row.company_count ? scope.row.company_count : "请导入" }}
              </div>
            </template>
          </el-table-column>

          <el-table-column align="center" label="操作" width="200">
            <template slot-scope="scope">
              <div v-if="scope.row.is_admin != 1">
                <el-button type="text" class="editText" @click="exitUser(scope.row, true)">查看</el-button>
                <el-button type="text" class="editText" @click="exitUser(scope.row, false)">修改</el-button>
                <el-button type="text" class="deletText" @click="passUser(scope.row.id)">重置密码
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination style="margin-top: 10px" :current-page="page" :page-size="limit" @current-change="currentChange"
          layout="prev, pager, next" :total="total">
        </el-pagination>
      </div>
    </div>
    <div v-show="activeName == 'branch'">
      <addDepartment></addDepartment>
    </div>
    <div v-show="activeName == 'street'">
      <street></street>
    </div>
    <div v-show="activeName == 'region'">
      <industryList :Listtype="1"></industryList>
    </div>
    <div v-show="activeName == 'industry'">
      <industryList :Listtype="2"></industryList>
    </div>
    <div v-show="activeName == 'demandSolve'">
      <demandSolve :options="tableData"></demandSolve>
    </div>


    <div v-show="activeName == 'questionService'">
      <div v-if="ConfigList.length">
        <Editor @input="onEditorChange" :value="ConfigList[2].value"></Editor>
        <div style="display: flex; margin-top: 20px">
          <div style="display: flex; align-items: center">请输入服务联系电话：</div>
          <el-input style="flex: 1" placeholder="请输入服务联系电话" v-model="ConfigList[1].value">
          </el-input>
        </div>
        <div style="display: flex; justify-content: flex-end; margin-top: 20px">
          <el-button type="primary" @click="saveData">保存</el-button>
        </div>
      </div>
    </div>
    <el-dialog :title="'创建账号'" :visible.sync="dialogupdate" :close-on-click-modal="false">
      <el-form :model="updateForm" :rules="rules" ref="ruleForm">
        <el-row>
          <el-col>
            <el-form-item label="头像" label-width="120px" prop="thumb">
              <el-upload class="avatar-uploader" :action="action" :show-file-list="false"
                :on-success="handleAvatarSuccessAdd" :before-upload="beforeAvatarUpload">
                <img v-if="updateForm.thumb" :src="updateForm.thumb" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="登录账号" label-width="120px" prop="login">
              <template slot-scope="scope">
                <el-input v-model="updateForm.login" autocomplete="off"></el-input>
              </template>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="账号名称 " label-width="120px" prop="name" v-if="type == 1">
              <template slot-scope="scope">
                <el-input v-model="updateForm.name" autocomplete="off"></el-input>
              </template>
            </el-form-item>
          </el-col>
          <el-col v-if="type != 1">
            <el-form-item label="部门" label-width="120px" prop="department_id">
              <template slot-scope="scope">
                <el-cascader :options="departmentList" v-model="department_idArr" @change="handleChange"
                  :props="{ value: 'id', label: 'name', checkStrictly: true }">
                </el-cascader>
              </template>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="省市区" label-width="120px" prop="region" v-if="type == 1">
              <el-cascader v-model="region" :props="props"></el-cascader>
            </el-form-item>
          </el-col>

          <el-col>
            <el-form-item v-if="type == 1" label="监控区域" label-width="120px" prop="name">
              <template slot-scope="scope">
                <el-input v-model="updateForm.back_name" autocomplete="off"></el-input>
              </template>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="联系人姓名" label-width="120px" prop="username">
              <el-input v-model="updateForm.username" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" label-width="120px" prop="mobile">
              <el-input v-model="updateForm.mobile" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" label-width="120px" prop="position">
              <el-input v-model="updateForm.position" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" label-width="120px" prop="email">
              <el-input v-model="updateForm.email" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col v-if="type == 1">
            <el-form-item label="有效期" label-width="120px" prop="over_onOld">
              <el-date-picker v-model="updateForm.over_onOld" type="daterange" value-format="yyyy-MM-dd"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="首页权限" label-width="120px" prop="url">
              <el-checkbox-group v-model="updateForm.checkedCities" @change="handleCheckedCitiesChange">
                <el-checkbox :disabled="city.id == 1 || seeType" v-for="city in updateForm.roleList" :label="city.id"
                  :key="city.id">{{ city.name }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>

          <el-col v-if="updateForm.checkedCities.indexOf(screenId) > 0">
            <el-form-item label="数据模版" label-width="120px" prop="url" v-if="this.$store.state.user.type == 1">
              <el-input v-model="updateForm.url" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="CreateUserInfo('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="seeType ? '查看用户信息' : '编辑用户信息'" :visible.sync="changeUseVisible" :close-on-click-modal="false">
      <el-form :model="changeUseData" :rules="rules1" ref="SetForm">
        <el-row>
          <el-col>
            <el-form-item label="头像" label-width="120px" prop="thumb">
              <el-upload class="avatar-uploader" :disabled="seeType" :action="action" :show-file-list="false"
                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="changeUseData.thumb" :src="changeUseData.thumb" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="登录账号" label-width="120px" prop="login">
              <template slot-scope="scope">
                <el-input disabled v-model="changeUseData.login" autocomplete="off"></el-input>
              </template>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item v-if="type == 1" label="账号名称 " label-width="120px" prop="name">
              <template slot-scope="scope">
                <el-input :disabled="seeType" v-model="changeUseData.name" autocomplete="off"></el-input>
              </template>
            </el-form-item>
          </el-col>
          <el-col v-if="type == 1">
            <el-form-item v-if="changeUseVisible" label="省市区" label-width="120px" prop="region">
              <el-cascader @change="regionChange" v-model="changeUseData.region" :props="props"
                :disabled="seeType"></el-cascader>
            </el-form-item>
          </el-col>

          <el-col>
            <el-form-item v-if="type == 1" label="监控区域" label-width="120px" prop="name">
              <template slot-scope="scope">
                <el-input v-model="changeUseData.back_name" :disabled="seeType" autocomplete="off"></el-input>
              </template>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="联系人姓名" label-width="120px" prop="username">
              <el-input :disabled="seeType" v-model="changeUseData.username" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" label-width="120px" prop="mobile">
              <el-input :disabled="seeType" v-model="changeUseData.mobile" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" label-width="120px" prop="position">
              <el-input :disabled="seeType" v-model="changeUseData.position" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" label-width="120px" prop="email">
              <el-input :disabled="seeType" v-model="changeUseData.email" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>

          <el-col v-if="type == 1">
            <el-form-item label="有效期" label-width="120px" prop="email">
              <el-date-picker :disabled="seeType" v-model="changeUseData.over_onOld" type="daterange"
                value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="首页权限" label-width="120px" prop="url">
              <el-checkbox-group v-model="changeUseData.checkedCities" @change="handleCheckedCitiesChange">
                <el-checkbox :disabled="city.id == 1 || seeType" v-for="city in changeUseData.roleList" :label="city.id"
                  :key="city.id">{{ city.name }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>

          <el-col v-if="changeUseData.checkedCities.indexOf(screenId) > 0">
            <el-form-item label="数据模版" label-width="120px" prop="url" v-if="this.$store.state.user.type == 1">
              <el-input :disabled="seeType" v-model="changeUseData.url" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setDataForm('SetForm')">{{
          seeType ? "关 闭" : "取 消"
        }}</el-button>
        <el-button v-if="!seeType" type="primary" @click="updateUserInfo('SetForm')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="重置密码" :visible.sync="dialogResetwrod" width="30%" @close="passwordClose">
      <div>提示：重置密码后，重置后新密码为登录账号</div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="passwordClose">取 消</el-button>
        <el-button type="primary" @click="passWord">确 定</el-button>
      </div>
    </el-dialog>
  </el-main>
</template>

<script>
import {
  userInfo,
  userDel,
  getAllProvince,
  userCreate,
  userEdit,
  userDepartmentList,
  getuserList,
  passWord,
  regionConfigList,
  regionConfig,
  userResetting,
  loginAll,
  roleList
} from "@/api/configApi";
import { mapGetters } from "vuex";
import { VUE_APP_BASE_API } from "@/config.js";
import addDepartment from "./addDepartment.vue";
import industryList from "./industryList.vue";
import street from "./street.vue";
import { getToken, setToken, removeToken } from "@/utils/auth";
import demandSolve from "./demandSolve.vue";

import Editor from "@/components/Editor";
export default {
  components: {
    addDepartment,
    Editor,
    demandSolve,
    industryList,
    street,
  },
  computed: {
    ...mapGetters(["type"]),
  },
  data() {
    // var validatorMobile = (rule, value, callback) => {
    //   if (!value) {
    //     return callback(new Error("请输入联系方式"));
    //   }
    //   //判断value是否为手机号
    //   if (!/^1[3456789]\d{9}$/.test(value)) {
    //     callback(new Error("请输入正确的手机号"));
    //   } else {
    //     callback();
    //   }
    // };
    // var validatorEmail = (rule, value, callback) => {
    //   if (!value) {
    //     return callback(new Error("请输入邮箱"));
    //   }
    //   //判断value是否为邮箱
    //   if (!/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/.test(value)) {
    //     callback(new Error("请输入正确的邮箱"));
    //   } else {
    //     callback();
    //   }
    // };

    let this_ = this;

    var regionList = (rule, value, callback) => {
      if (this.region.length < 1) {
        callback(new Error("请选择省市区"));
      } else {
        callback();
      }
    };

    var regionLogin = (rule, value, callback) => {
      if (this.isAlphaNumSpecial(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的登录账号，只含有数字字母和特殊字符中的‘-’和‘_’"));
      }
    };

    var regionList2 = (rule, value, callback) => {
      if (this.changeUseData.region.length < 1) {
        callback(new Error("请选择省市区"));
      } else {
        callback();
      }
    };
    return {
      addTime: {
        start_time: '',
        over_on: ''
      },

      screenId: '',

      ConfigList: [],
      ophoneNumber: "",
      activeName: "user",
      department_id: "",
      departmentList: [],
      department_idArr: [],
      action: VUE_APP_BASE_API + "/v1/config/upload",
      region: [],
      props: {
        lazy: true,
        checkStrictly: true,
        lazyLoad(node, resolve) {
          const { level, path } = node;
          getAllProvince({
            area_code_id: level ? path[path.length - 1] : 1,
          }).then((res) => {
            const nodes = res.map((item) => ({
              value: item.id,
              label: item.name,
              leaf: level >= 2,
            }));
            resolve(nodes);
          });
        },
      },
      keywords: "",
      page: 1,
      limit: 10,
      total: 0,
      rules: {
        username: [
          {
            required: true,
            message: "请输入联系人姓名",
            trigger: "blur",
          },
        ],
        login: [{ required: true, validator: regionLogin, trigger: "blur" }],
        position: [{ message: "请输入职位", trigger: "blur" }],
        mobile: [{ required: true, message: "请输入联系方式", trigger: "blur" }],
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        region: [{ required: true, validator: regionList, trigger: "change" }],
        name: [{ required: true, message: "请输入账号名称 ", trigger: "blur" }],
        department_id: [{ required: true, message: "请选择部门", trigger: "blur" }],
        over_onOld: [{ required: true, message: "请选择有效期", trigger: "blur" }],
      },
      rules1: {
        username: [
          {
            required: true,
            message: "请输入联系人姓名",
            trigger: "blur",
          },
        ],
        login: [{ required: true, validator: regionLogin, trigger: "blur" }],
        position: [{ message: "请输入职位", trigger: "blur" }],
        mobile: [{ required: true, message: "请输入联系方式", trigger: "blur" }],
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        region: [{ required: true, validator: regionList2, trigger: "change" }],
        name: [{ required: true, message: "请输入账号名称 ", trigger: "blur" }],
        over_onOld: [{ required: true, message: "请选择有效期", trigger: "blur" }],
        department_id: [{ required: true, message: "请选择部门", trigger: "blur" }],
      },
      id: this.$store.state.user.id,
      currentUserdata: {},
      tableData: [],
      dialogupdate: false,
      updateForm: {
        department_id: "",
        username: "",
        position: "",
        mobile: "",
        email: "",
        login: "",
        is_admin: "",
        name: "",
        province: "",
        city: "",
        area: "",
        thumb: "",
        back_name: "",
        over_onOld: [],
        over_on: "",
        start_time: "",
        url: '',
        checkedCities: [],
        roleList: [],
        role: ''
      },
      dialogResetwrod: false,
      changeUseVisible: false,
      changeUseData: {
        login: "",
        user_id: "",
        thumb: "",
        username: "",
        position: "",
        mobile: "",
        email: "",
        is_queue: "",
        name: "",
        region: [],
        province: "",
        city: "",
        back_name: "",
        area: "",
        over_onOld: [],
        start_time: "",
        over_on: "",
        url: '',
        checkedCities: [],
        roleList: [],
        role: ''
      },
      passwordUserId: "",
      seeType: false,

      content: `<p>这是 vue-quill-editor 的内容！</p>`, //双向数据绑定数据
      editorOption: {
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
            ["blockquote", "code-block"], // 引用  代码块
            [{ header: 1 }, { header: 2 }], // 1、2 级标题
            [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
            [{ script: "sub" }, { script: "super" }], // 上标/下标
            [{ indent: "-1" }, { indent: "+1" }], // 缩进
            [{ direction: "rtl" }], // 文本方向
            [{ size: ["12px", false, "16px", "18px", "20px", "30px"] }], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
            [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
            [
              {
                font: [
                  false,
                  "SimSun",
                  "SimHei",
                  "Microsoft-YaHei",
                  "KaiTi",
                  "FangSong",
                  "Arial",
                ],
              },
            ], // 字体种类
            [{ align: [] }], // 对齐方式
            ["clean"], // 清除文本格式
            ["link", "image", "video"], // 链接、图片、视频
          ],
          placeholder: "请输入正文",
        },
      },


    };
  },
  async mounted() {
    this.getuserList();
    // newsinfo({ id: this.id }).then((res) => {
    //   this.currentUserdata = res;
    // });
    roleList().then(res => {
      this.updateForm.roleList = res
      res.map(res => {
        if (res.name == '数据') {
          this.screenId = res.id
        }
      })
    })
  },
  methods: {
    handleCheckedCitiesChange(value) {
      console.log(this.changeUseData.checkedCities);
      console.log(this.updateForm.checkedCities);
    },
    saveData() {
      regionConfig(
        {
          type: this.ConfigList[1].type,
          value: this.ConfigList[1].value,
        }
      ).then(async res => {
        await regionConfig(
          {
            type: this.ConfigList[2].type,
            value: this.ConfigList[2].value,
          }
        )
        this.$message({
          message: "保存成功",
          type: "success",
        });

      })
    },
    // 失去焦点事件
    onEditorBlur(quill) {
      console.log("editor blur!", quill);
    },
    // 获得焦点事件
    onEditorFocus(quill) {
      console.log("editor focus!", quill);
    },
    // 准备富文本编辑器
    onEditorReady(quill) {
      console.log("editor ready!", quill);
    },
    // 内容改变事件
    onEditorChange(html) {
      this.ConfigList[2].value = html;
    },

    isAlphaNumSpecial(str) {
      // 正则表达式，匹配字母、数字、特殊符号"-"和"_"
      return /^[a-zA-Z0-9-_]+$/.test(str);
    },
    ImportCompany(id) {
      this.$router.push({
        path: "/ImportCompany",
        query: {
          id: id,
        },
      });
    },
    passWord() {
      userResetting({ user_id: this.passwordUserId })
        .then((res) => {
          this.dialogResetwrod = false;
          this.$message({
            message: "修改成功",
            type: "success",
          });
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
    handleClick(tab, event) {
      if (tab.name == "questionService") {
        regionConfigList().then((res) => {
          this.ConfigList = res;
        });
      }
    },
    handleChange(data) {
      console.log(data);
      console.log(data[data.length - 1]);
      this.updateForm.department_id = data[data.length - 1];
    },
    addDepartment() {
      this.$router.push(`/addDepartment`);
    },
    updateUserInfo(formName) {
      //this.formName.checkedCities 去重
      this.changeUseData.checkedCities = Array.from(new Set(this.changeUseData.checkedCities))

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.changeUseData.over_on = this.changeUseData.over_onOld[1];
          this.changeUseData.start_time = this.changeUseData.over_onOld[0];
          this.changeUseData.role = this.changeUseData.checkedCities.join(',')
          let form = {
            ...this.changeUseData,
            is_admin: this.type == "1" ? "1" : "",
          };
          console.log(form, "form");
          userEdit(form).then((res) => {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.getuserList();
            this.changeUseVisible = false;
          });
        }
      });
    },
    handleAvatarSuccess(res, file) {
      this.changeUseData.thumb = file.response.data.url;
    },
    handleAvatarSuccessAdd(res, file) {
      this.updateForm.thumb = file.response.data.url;
    },
    beforeAvatarUpload(file) {
      console.log(file.type);
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      console.log(isJPG, isPNG);
      if (!(isJPG || isPNG)) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      return isJPG || isPNG;
    },
    regionChange() {
      this.changeUseData.province = this.changeUseData.region[0]
        ? this.changeUseData.region[0].toString()
        : "";
      this.changeUseData.city = this.changeUseData.region[1]
        ? this.changeUseData.region[1].toString()
        : "";
      this.changeUseData.area = this.changeUseData.region[2]
        ? this.changeUseData.region[2].toString()
        : "";
    },
    currentChange(page) {
      this.page = page;
      this.getuserList();
    },
    getuserList() {
      getuserList({
        page: this.page,
        limit: this.limit,
        keywords: this.keywords,
      }).then((res) => {
        this.tableData = res.list;
        this.total = res.count;


        this.addTime.start_time = res.myself.start_time
        this.addTime.over_on = res.myself.over_on
        this.tableData.unshift(res.myself);

        this.tableData = this.tableData.map((item, index) => {
          //判断是否禁用
          if (item.switch == 1) {
            item.switch = true;
          } else if (item.switch == 0) {
            item.switch = false;
          }

          //判断权限
          if (item.is_queue == 1) {
            item.is_queue = true;
          } else if (item.is_queue == 0) {
            item.is_queue = false;
          }
          return item;
        });
      });
    },
    addUser() {
      this.region = [];

      this.updateForm = {
        department_id: this.type == 1 ? 0 : "",
        username: "",
        position: "",
        mobile: "",
        email: "",
        login: "",
        is_admin: this.type == 1 ? 1 : "",
        name: "",
        province: "",
        city: "",
        area: "",
        thumb: "",
        back_name: "",
        over_on: "",
        over_onOld: [],
        start_time: "",
        url: '',
        checkedCities: [1, 2, 3, 4, 5, 6],
        roleList: this.updateForm.roleList,
        role: ''
      };

      console.log(this.type, "this.type");
      if (this.type != 1) {
        userDepartmentList().then((res) => {
          this.departmentList = res.list;
          console.log(this.departmentList, "部门列表");
        });
      }

      this.dialogupdate = true;
    },
    exitUser(item, seeType) {
      userInfo({
        user_id: item.id,
      }).then((res) => {
        console.log(res);
        let {
          id,
          thumb,
          username,
          mobile,
          position,
          email,
          is_queue,
          over_on,
          login,
          start_time,

        } = res.info;
        let { name, province, city, area, back_name, url } = res.region;

        this.changeUseData.user_id = id;
        this.changeUseData.thumb = thumb;
        this.changeUseData.username = username;
        this.changeUseData.position = position;
        this.changeUseData.mobile = mobile;
        this.changeUseData.email = email;
        this.changeUseData.is_queue = is_queue;
        this.changeUseData.name = name;
        this.changeUseData.province = province;
        this.changeUseData.city = city;
        this.changeUseData.area = area;
        this.changeUseData.login = login;
        this.changeUseData.url = url;
        this.changeUseData.roleList = res.role;
        this.changeUseData.roleList.map(res_ => {
          if (res_.is_show == 1) {
            this.changeUseData.checkedCities.push(res_.id)
          }
        })
        console.log(this.changeUseData.role, 'this.changeUseData.role');

        this.changeUseData.back_name = back_name;

        this.changeUseData.over_on = over_on;
        this.changeUseData.start_time = start_time;

        // this.changeUseData.over_onOld = [start_time ? start_time : '', over_on ? over_on : ''];
        this.$set(this.changeUseData, "over_onOld", [
          start_time ? start_time : "",
          over_on ? over_on : "",
        ]);



        this.changeUseData.region = [];
        if (Number(province)) {
          this.changeUseData.region.push(Number(province));
        }
        if (Number(city)) {
          this.changeUseData.region.push(Number(city));
        }
        if (Number(area)) {
          this.changeUseData.region.push(Number(area));
        }

        this.changeUseVisible = true;
        this.seeType = seeType;

        console.log(this.changeUseData.region, "this.changeUseData");
      });
    },
    isDateExpired(dateString) {
      var date = new Date(dateString);
      var currentDate = new Date();
      return date < currentDate;
    },
    CreateUserInfo(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.type == 1) {
            this.updateForm.province = this.region[0] ? this.region[0].toString() : "";
            this.updateForm.city = this.region[1] ? this.region[1].toString() : "";
            this.updateForm.area = this.region[2] ? this.region[2].toString() : "";
          }

          if (this.updateForm.over_onOld.length) {
            this.updateForm.start_time = this.updateForm.over_onOld[0];
            this.updateForm.over_on = this.updateForm.over_onOld[1];
          }
          if (this.$store.state.user.type == 2) {
            this.updateForm.start_time = this.addTime.start_time
            this.updateForm.over_on = this.addTime.over_on
          }
          this.updateForm.role = this.updateForm.checkedCities.join(',')

          userCreate(this.updateForm)
            .then((res) => {
              this.dialogupdate = false;
              this.getuserList();
              this.$message({
                message: "账号已创建，默认密码为登录账号。请登录后修改",
                type: "success",
              });
              this.department_idArr = [];
            })
            .catch((err) => {
              this.$message.error(err.message);
            });
        } else {
          return false;
        }
      });
    },
    passUser(id) {
      this.dialogResetwrod = true;
      this.passwordUserId = id;
    },
    updataState(id) {
      userDel({ user_id: id, type: 2 }).then((res) => {
        this.getuserList(this.id);
      });
    },
    updataQueue(id) {
      userDel({ user_id: id, type: 3 }).then((res) => {
        this.getuserList(this.id);
      });
    },
    passwordClose() {
      this.dialogResetwrod = false;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogupdate = false;
    },
    setDataForm(formName) {
      this.$refs[formName].resetFields();
      this.changeUseVisible = false;
      // this.changeUseData = {
      //   user_id: "",
      //   thumb: "",
      //   username: "",
      //   position: "",
      //   mobile: "",
      //   email: "",
      //   is_queue: "",
      //   name: "",
      //   region: [],
      //   province: "",
      //   city: "",
      //   back_name: "",
      //   area: "",
      //   over_on: "",
      //   url: '',
      //   checkedCities: [],
      //   roleList: [],
      //   role: ''
      // };
    },
    setToken(item) {
      loginAll({
        login: item.login
      }).then(res => {
        console.log(res)
        let token = res.token
        const news = this.$router.resolve({ path: "/#/home" });
        window.location.href = news.location.path;
        sessionStorage.setItem("tokens", getToken());
        sessionStorage.setItem("is_admin_view", 1);
        setToken(token);
      })
    }
  },
};
</script>

<style scoped lang="less">
::v-deep .el-cascader {
  width: 100%;
}

::v-deep .el-dialog__body {
  padding: 30px 20px 0px 20px;
}

.el-main {
  margin: 30px 15px;
}

.password_span {
  color: red;
  font-size: 12px;
  position: absolute;
  right: 0;
  top: 80%;
}

::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 125px;
  height: 125px;
  line-height: 125px;
  text-align: center;
}

.avatar {
  width: 125px;
  height: 125px;
  display: block;
}

/*加上height和滚动属性就可以，滚动条样式是系统默认样式，可能不同*/
.ql-toolbar.ql-snow .ql-picker.ql-expanded .ql-picker-options {
  border-color: #ccc;
  height: 125px;
  overflow: auto;
}

.company_count:hover {
  color: #409eff;
}

.over_on {
  background-color: #ff0000;
  color: #fff;
  font-size: 10px;
  padding: 3px 5px;
  border-radius: 5px;
  font-weight: bold;
}
</style>
